package com.java1412.controller;

import com.java1412.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author java1412
 * @create 2022-09-02 9:59
 */
@Slf4j
@RestController
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @GetMapping("/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id) {
        String result = paymentService.paymentInfo_OK(id);
        log.info("******result: " + result);
        return result;
    }

    // 如果需要进行服务降级需要使用该注解
    // fallbackMethod：使用哪个方法进行服务降级
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler", commandProperties = {
            // 我们这个方法最多容忍三秒，超过三秒自动执行服务降级方法paymentInfo_TimeOutHandler
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    @GetMapping("/payment/hystrix/timeout/{id}")
    public String paymentInfo_Timeout(@PathVariable("id") Integer id) {
//        String result = paymentService.paymentInfo_Timeout(id);
//        log.info("******result: " + result);
//        return result;
        int timeNumber = 5;
        // 测试超时情况
//        try {
//            TimeUnit.SECONDS.sleep(timeNumber);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        // 测试异常情况
        int i = 1 / 0; // 出现异常也会进行服务降级
        return "线程池 : " + Thread.currentThread().getName()
                + "\t paymentInfo_TimeOutHandler,id : " + id + ",耗时 : " + timeNumber + " 秒";
    }

    // 添加服务降级的处理的方法
    public String paymentInfo_TimeOutHandler(Integer id) {
        return "8001提供者，线程池 : " + Thread.currentThread().getName()
                + "\t paymentInfo_TimeOutHandler,系统繁忙，请稍后再试,id : " + id;
    }

    @GetMapping("/payment/circuit/{id}")
    public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
        String result = paymentService.paymentCircuitBreaker(id);
        log.info("******result：" + result);
        return result;
    }
}
